package cn.yunhe.mybatis;

import cn.yunhe.dao.PersonDao;
import cn.yunhe.dao.RoleMapper;
import cn.yunhe.model.Person;
import cn.yunhe.model.Role;
import cn.yunhe.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zs on 2017/11/27.
 */
public class Demo {

    /**
     * 测试注解mybatis
     */
    @Test
    public void test1() {
        SqlSession session = SqlSessionFactoryUtil.getSqlSession();
        PersonDao personDao = session.getMapper(PersonDao.class);
        Person person = personDao.getPerson(1);
        System.out.println(person.getUsername());
    }

    /**
     * 测试mybatis
     */
    @Test
    public void test2() {
        Logger log = Logger.getLogger(Demo.class);
        SqlSession session = null;

        try {
            session = SqlSessionFactoryUtil.getSqlSession();
            RoleMapper roleMapper = session.getMapper(RoleMapper.class);
            Role role = roleMapper.getRole(1L);
            log.info(role.getRoleName());
        } finally {
            if (session != null) {
                session.close();
            }
        }

    }

    /**
     * 测试多参数传递
     */
    @Test
    public void test3() {
        SqlSession session = SqlSessionFactoryUtil.getSqlSession();
        RoleMapper roleMapper = session.getMapper(RoleMapper.class);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("roleName", "超");
        params.put("note", "1");
        List<Role> list = roleMapper.findRoleByMap(params);

        for (Role r : list) {
            System.out.println(r.getRoleName());
        }
    }


    /**
     * 分页参数 rowBounds
     */
    @Test
    public void test4() {
        SqlSession session = SqlSessionFactoryUtil.getSqlSession();
        RoleMapper roleMapper = session.getMapper(RoleMapper.class);
        RowBounds rowBounds = new RowBounds(0, 4);
        List<Role> roleList = roleMapper.findByRowBounds("", "", rowBounds);

        for (Role role : roleList) {
            System.out.println(role.getRoleName());
        }
    }

    /**
     * 主键回填
     */
    @Test
    public void test5() {
        SqlSession session = SqlSessionFactoryUtil.getSqlSession();
        RoleMapper roleMapper = session.getMapper(RoleMapper.class);
        Role role = new Role();
        role.setRoleName("秘书");
        role.setNote("666");
        roleMapper.insertRole(role);
        System.out.println(role.getId());

        session.commit();
    }


}
